#include "VolumeEncoder.h"
#include "OCMain/OCMath.h"

namespace OCPP
{
	namespace Volume
	{
		VolumeEncoder::EncodeRange VolumeEncoder::EncodeRangeNone = { 0.0f,0.0f };
		VolumeEncoder::EncodeRange VolumeEncoder::EncodeRangeDBZ = { 0.0f,70.0f };
		VolumeEncoder::EncodeRange VolumeEncoder::EncodeRangeWind = { 0.0f,60.0f };
		VolumeEncoder::EncodeRange VolumeEncoder::EncodeRangeVerticalWind = { -5.0f,5.0f };
		VolumeEncoder::EncodeRange VolumeEncoder::EncodeRangeTemperature = { -20.0f,40.0f };
		VolumeEncoder::EncodeRange VolumeEncoder::EncodeRangePercent = { 0.0f,100.0f };
		VolumeEncoder::EncodeRange VolumeEncoder::EncodeRangeSH = { 0.0f,0.02f };

		String VolumeEncoder::EncodeRangeToString(EncodeRange _encodeRange)
		{
			const auto& [minValue, maxValue] = _encodeRange;
			return str_format("%.2f,%.2f", minValue, maxValue);
		}

		VolumeEncoder::EncodeRange VolumeEncoder::EncodeRangeFromString(String str)
		{
			StringVector sv = StringUtil::split(str, ",");
			if (sv.size() == 2)
			{
				String minValue = sv[0];
				StringUtil::trim(minValue);
				String maxValue = sv[1];
				StringUtil::trim(maxValue);
				return {
					(float)std::atof(minValue.c_str()),
					(float)std::atof(maxValue.c_str())
				};
			}

			return EncodeRangePercent;
		}

		inline float frac(float value)
		{
			return value - floor(value);
		}

		uint8 VolumeEncoder::encodeInRange(float value, VolumeEncoder::EncodeRange encRange)
		{
			float minValue = std::get<0>(encRange);
			float maxValue = std::get<1>(encRange);
			float valueInRange = Math::Clamp(value, minValue, maxValue);
			float valueToEncode = (valueInRange - minValue) / (maxValue - minValue);
			return (uint8)round(valueToEncode * 255.0f);
		}

		Uint8Vector VolumeEncoder::encodeUV(float valueU, float valueV)
		{
			float uInRange = Math::Clamp(valueU, -127.0f, 127.0f) + 127.0f;
			float vInRange = Math::Clamp(valueV, -127.0f, 127.0f) + 127.0f;
			return {
				(uint8)floor(uInRange),
				(uint8)(frac(valueU) * 255.0f),
				(uint8)floor(vInRange),
				(uint8)(frac(valueV) * 255.0f)
			};
		}
	}
}


